const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");
const fs = require('fs');
const stringRandom = require("string-random")

router.get("/", async (ctx) => {
    ctx.body = "你是猪吗";

/*
图片审验画面接口
 */
}).post("/addPictureTagging", async (ctx) => {
    const file = ctx.request.files.file;
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let mediaId = ctx.request.body.mediaId

    let data = await DB.uploadFile(file.path, mediaId);
    if (data["_id"] != null) {
        try {
            console.log(time + "：" + mediaId + " GridFS保存审验成功!");
            let list = {
                "mediaId": mediaId,
                "fileId": data["_id"],
            };
            let data2 = await DB.insert('tagging', list);
            if (data2.result.ok) {
                ctx.body = 1;
                console.log(time + "：添加审验成功" + mediaId);
            } else {
                ctx.body = 0;
            }
        } catch (e) {
            console.log(time + "：" + e);
        }
    } else
        ctx.body = 0;

}).post("/updatePictureTagging", async (ctx) => {
    const file = ctx.request.files.file;
    let mediaId = ctx.request.body.mediaId;
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');

    let data = await DB.uploadFile(file.path, mediaId);
    if (data["_id"] != null) {
        try {
            console.log(time + "：" + mediaId + " GridFS保存审验成功!");
            let data2 = await DB.findSomeCol('tagging', {'mediaId': mediaId}, {"_id": 0, "fileId": 1});
            let fileId = data2[0]["fileId"];
            let data3 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
            let data4 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
            if (data3.result.ok && data4.result.ok) {
                let data5 = await DB.update('tagging', {'mediaId': mediaId}, {'fileId': data["_id"]})
                if (data5.result.ok) {
                    ctx.body = 1;
                    console.log(time + "：修改审验成功" + mediaId);
                } else {
                    ctx.body = 0;
                }
            } else
                ctx.body = 0;
        } catch (e) {
            console.log(time + "：" + e);
        }
    } else
        ctx.body = 0;

}).get("/deletePictureTagging", async (ctx) => {
    // console.log(ctx.request.body);
    let mediaId = ctx.query["mediaId"];
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let data = await DB.findSomeCol('tagging', {"mediaId": mediaId}, {"_id": 0, "fileId": 1});
    let fileId = data[0]["fileId"];
    // console.log(mediaId);
    // console.log(data[0]["fileId"]);
    let data1 = await DB.remove1('tagging', {"mediaId": mediaId});
    if (data1.result.ok) {
        let data2 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
        let data3 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
        if (data2.result.ok && data3.result.ok) {
            ctx.body = 1;
            console.log(time + "：删除审验成功" + mediaId);
        } else {
            ctx.body = 0;
            console.log(time + "：删除审验失败" + mediaId);
        }
    } else {
        ctx.body = 0;
        console.log(time + "：删除审验失败" + mediaId);
    }

}).get("/getPictureTagging", async (ctx) => {
    let mediaId = ctx.query["mediaId"];
    let randomStr = stringRandom(16)
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    console.log(time + ":" + randomStr)
    let data = await DB.find('tagging', {"mediaId": mediaId});
    if (data.length !== 0) {
        let data2 = await DB.downloadFile(data[0]["fileId"], '/tmp/'+randomStr);
        if (data2 !== 1){
            ctx.body = 0;
        } else {
            const readfilePromise = new Promise((resolve, reject) => {
                fs.readFile('/tmp/'+randomStr, function(err, data){
                    if (err)
                        return reject(err);
                    resolve(data)
                })
            });
            await readfilePromise.then(data => ctx.body = data, err => console.log(err));
        }
    } else
        ctx.body = 0;


/*
视频审验画面接口
 */
}).post("/addMediaTagging", async (ctx) => {
    const file = ctx.request.files.file;
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let mediaId = ctx.request.body.mediaId;
    let frame = ctx.request.body.frame;
    let videoTime = ctx.request.body.videoTime

    let data = await DB.uploadFile(file.path, mediaId + ":" + frame);
    if (data["_id"] != null) {
        try {
            console.log(time + "：" + mediaId + ":" + frame + " GridFS保存审验成功!");
            let list = {
                "mediaId": mediaId,
                "frame": frame,
                "fileId": data["_id"],
                "videoTime": videoTime
            };
            let data2 = await DB.insert('tagging', list);
            if (data2.result.ok) {
                ctx.body = {id: data2.ops[0]._id, fileId: data["_id"]};
                console.log(time + "：添加审验成功" + mediaId + ":" + frame);
            } else {
                ctx.body = 0;
            }
        } catch (e) {
            console.log(time + "：" + e);
        }
    } else
        ctx.body = 0;

}).post("/updateMediaTagging", async (ctx) => {
    const file = ctx.request.files.file;
    let mediaId = ctx.request.body.mediaId;
    let frame = ctx.request.body.frame;
    let fileId = ctx.request.body.fileId
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');

    let data = await DB.uploadFile(file.path, mediaId + ":" + frame);
    if (data["_id"] != null) {
        try {
            console.log(time + "：" + mediaId + ":" + frame + " GridFS保存审验成功!");
            let data3 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
            let data4 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
            if (data3.result.ok && data4.result.ok) {
                let data5 = await DB.update('tagging', {'mediaId': mediaId, 'frame': frame}, {'fileId': data["_id"]})
                if (data5.result.ok) {
                    ctx.body = 1;
                    console.log(time + "：修改审验成功" + mediaId + ":" + frame);
                } else {
                    ctx.body = 0;
                }
            } else
                ctx.body = 0;
        } catch (e) {
            console.log(time + "：" + e);
        }
    } else
        ctx.body = 0;

}).get("/deleteMediaTagging", async (ctx) => {
    // console.log(ctx.request.body);
    let mediaId = ctx.query["mediaId"];
    let frame = ctx.query["frame"];
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let fileId = ctx.query["fileId"];
    // console.log(mediaId);
    // console.log(data[0]["fileId"]);
    let data1 = await DB.remove1('tagging', {'mediaId': mediaId, 'frame': frame});
    if (data1.result.ok) {
        let data2 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
        let data3 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
        if (data2.result.ok && data3.result.ok) {
            ctx.body = 1;
            console.log(time + "：删除审验及其评论成功" + mediaId + frame);
        } else {
            ctx.body = 0;
            console.log(time + "：删除审验及其评论失败" + mediaId + frame);
        }
    } else {
        ctx.body = 0;
        console.log(time + "：删除审验及其评论失败" + mediaId + frame);
    }

}).get("/getMediaTagging", async (ctx) => {
    let fileId = ctx.query["fileId"];
    let randomStr = stringRandom(16)
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    console.log(time + ":" + randomStr)
    let data = await DB.downloadFile(DB.getObjectId(fileId), '/tmp/'+randomStr);
    if (data !== 1){
        ctx.body = 0;
    } else {
        const readfilePromise = new Promise((resolve, reject) => {
            fs.readFile('/tmp/'+randomStr, function(err, data){
                if (err)
                    return reject(err);
                resolve(data)
            })
        });
        await readfilePromise.then(data => ctx.body = data, err => console.log(err));
    }

}).get("/getMediaTaggingList", async (ctx) => {
    let mediaId = ctx.query["mediaId"];
    ctx.body = await DB.find('tagging', {'mediaId': mediaId});

});

module.exports = router.routes();
